package com.micro.frog.acct.service.impl;

import com.micro.frog.acct.dao.RoleMenuMapper;
import com.micro.frog.acct.entity.RoleMenu;
import com.micro.frog.acct.service.RoleMenuService;
import com.micro.frog.acct.vo.RoleMenuVO;
import com.micro.frog.core.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author :  ljh
 * @date : 2018/4/12
 **/
@Service
public class RoleMenuServiceImpl implements RoleMenuService {

    @Autowired
    RoleMenuMapper roleMenuMapper;

    @Override
    public List<Integer> queryRoleMenu(Integer roleId) {
        List<Integer> list = new ArrayList<>();
        RoleMenu roleMenu = new RoleMenu();
        roleMenu.setRoleId(roleId);
        List<RoleMenu> menus = roleMenuMapper.selectByCondition(roleMenu);
        for (RoleMenu menu : menus) {
            list.add(menu.getMenuId());
        }
        return list;
    }

    @Override
    public void addRoleMenus(Integer roleId, List<Integer> menuIds) {
        for (Integer menuId : menuIds) {
            if (null != menuId){
                RoleMenu userRole = new RoleMenu();
                userRole.setRoleId(roleId);
                userRole.setMenuId(menuId);
                roleMenuMapper.insertSelective(userRole);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void updateRoleMenus(Integer roleId, String menuIds) {
        roleMenuMapper.deletedByRoleId(roleId);
        if (!StringUtils.isEmpty(menuIds)){
            for (String menuId : menuIds.split(",")) {
                if (null != menuId){
                    RoleMenu userRole = new RoleMenu();
                    userRole.setRoleId(roleId);
                    userRole.setMenuId(Integer.parseInt(menuId));
                    roleMenuMapper.insertSelective(userRole);
                }
            }
        }
    }

    @Override
    public List<RoleMenu> all(RoleMenu roleMenu) {
        return roleMenuMapper.selectByCondition(roleMenu);
    }

    @Override
    public int add(RoleMenu roleMenu) {
        return roleMenuMapper.insertSelective(roleMenu);
    }

    @Override
    public int delete(Integer id) {
        return roleMenuMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(RoleMenu roleMenu) {
        return roleMenuMapper.updateByPrimaryKeySelective(roleMenu);
    }
}
